import React, { useEffect, useState } from 'react';
import { Button, Drawer, message, Spin, Tree } from 'antd';
import { selectAuthority, saveRoleAuth } from '@/services/role';
import { TreeNode } from 'antd/es/tree-select';
import PubSub from 'pubsub-js';
const TreeNode = Tree.TreeNode;

const RoleDrawer: React.FC<any> = props => {
  const [loading, setLoading] = useState<any>(false);

  const [allRole, setAllRole] = useState<any>([]);
  const [checkRole, setCheckRole] = useState<any>([]);
  const [halfCheck, setHalfCheck] = useState<any>([]);

  useEffect(() => {
    if (props.roleId) {
      setLoading(true);
      selectAuthority({ id: props.roleId }).then((res: any) => {
        if (res.status === 0) {
          setAllRole(res.data.all);
          let checkIds: any = [];
          deepRole(res.data.all, res.data.role, checkIds);
          setCheckRole(checkIds);
        } else {
          message.error(res.msg);
        }
        setLoading(false);
        // console.log()
      });
    }
  }, [props.roleId]);

  const deepRole = (roles: any, checks: any, checkIds: any) => {
    let rs = true;
    roles.forEach((item: any) => {
      if (item.children && item.children.length > 0) {
        if (!deepRole(item.children, checks, checkIds)) {
          rs = false;
        } else {
          let checkId = findRoleId(item.id, checks);
          if (checkId) {
            checkIds.push(checkId);
          } else {
            rs = false;
          }
        }
      } else {
        let checkId = findRoleId(item.id, checks);
        if (checkId) {
          checkIds.push(checkId);
        } else {
          rs = false;
        }
      }
    });
    return rs;
  };

  const findRoleId = (id: number, checks: any) => {
    let role = checks.find((item: any) => item.id === id);
    return role ? role.id : null;
  };

  let onCheck = (checkedKeys: any, e: any) => {
    setCheckRole(checkedKeys);
    setHalfCheck(e.halfCheckedKeys);
  };

  let renderTreeNodes = (data: any): any => {
    if (!data) {
      return;
    }
    return data.map((item: any) => {
      if (item.children) {
        return (
          <TreeNode title={item.menuName} key={item.id} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.menuName} />;
    });
  };

  let toggleDrawer = () => {
    PubSub.publish('toggleDrawer', false);
  };

  let saveRoles = () => {
    console.log([...checkRole, ...halfCheck]);
    setLoading(true);
    saveRoleAuth({ id: props.roleId, ids: JSON.stringify([...checkRole, ...halfCheck]) }).then(
      (res: any) => {
        if (res.status === 0) {
          message.success('权限更新成功');
        } else {
          message.error(res.msg);
        }
        setLoading(false);
      },
    );
  };

  return (
    <Drawer
      title="角色权限"
      destroyOnClose={true}
      maskClosable={true}
      width={520}
      onClose={() => {
        toggleDrawer();
      }}
      visible={props.drawerShow}
      bodyStyle={{ paddingBottom: 80 }}
    >
      <Spin spinning={loading}>
        {allRole && allRole.length > 0 && (
          <Tree
            checkable
            multiple={true}
            defaultExpandAll={true}
            checkedKeys={checkRole}
            onCheck={onCheck}
            selectable={false}
            // checkStrictly={true}
          >
            {renderTreeNodes(allRole)}
          </Tree>
        )}

        <div>
          <Button type="primary" onClick={saveRoles}>
            保存权限
          </Button>
        </div>
      </Spin>
    </Drawer>
  );
};

export default RoleDrawer;
